package ar.edu.itba.pod.legajo48013.event;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Date;

import ar.edu.itba.event.EventInformation;
import ar.edu.itba.event.RemoteEventDispatcher;
import ar.edu.itba.pod.agent.runner.Agent;
import ar.edu.itba.pod.multithread.MultiThreadEventDispatcher;

/**
 * Event dispatcher
 */
public class ClusterEventDispatcher extends MultiThreadEventDispatcher {

	private RemoteEventDispatcher remoteDispatcher;
	private String nodeId; 

	public ClusterEventDispatcher(String nodeId, RemoteEventDispatcher remoteDispatcher) {
		super();
		this.nodeId = nodeId;
		this.remoteDispatcher = remoteDispatcher;
	}
	
	@Override
	public void publish(Agent source, Serializable event) throws InterruptedException {
		EventInformation eventInfo = new EventInformation(event, nodeId, source);
		eventInfo.setReceivedTime(new Date().getTime());
		try {
			remoteDispatcher.publish(eventInfo);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void publishLocal(EventInformation event) throws InterruptedException{
		super.publish(event.source(), event.event());
	}
	
}
